import { computed, ref, reactive, Ref, inject } from 'vue'
import { Widget } from '@/models'
import { Viewer, WidgetType } from '@/types'
import { GLOBAL_KEYBOARD } from '../contract/hotkey/useHotkey'

/** 控件状态 */
export default function useWidgetState(data: Ref<Widget>) {
  /** 合同控件 */
  const viewer = inject('Viewer') as Viewer

  /** 是否激活 */
  const active = computed(() => data.value.isActivated)

  /** 鼠标悬浮 */
  const hovering = ref(false)

  return reactive({
    /** 是否激活 */
    active,

    /** 鼠标悬浮 */
    hovering,

    /**
     * 是否显示控件
     * 填写控件已完成模式如果未填写内容需要隐藏，表格控件除外
     */
    isShow: computed(() => {
      const widget = data.value
      return !(widget.isFill && widget.isDone && !widget.hasFillValue && widget.type !== WidgetType.TABLE)
    }),

    /** 填写控件展示必填 */
    showRequired: computed(() => {
      const widget = data.value
      return widget.required && widget.isFill && !widget.isDone
    }),

    /** 控件自定义类名 */
    customClassName: computed(() => viewer.widgetClassName?.(data.value)),

    /** 激活 */
    activate: () => {
      if (viewer.selection.list.length) return

      // Ctrl/Cmd 点击不聚焦
      if (GLOBAL_KEYBOARD.ctrlKey || GLOBAL_KEYBOARD.metaKey) return

      data.value.isActivated = true
    }
  })
}
